/* eslint-disable react-refresh/only-export-components */
import React, { useState } from "react";
import { NavBar, SearchBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import styles from "./css/city.module.css";
import CityTop from "./components/CityTop";
import { getCity, getCityLocation, searchCity } from "../../api/info";
import Citylist from "./components/Citylist";
import { setCity } from "../../store/slice/ticketSlice";
import { useDispatch } from "react-redux";
import { useFd } from "../../hooks";
import CitySearch from "./components/CitySearch";
import SearchHistory from "./components/SearchHistory";

function Index() {
  let dis = useDispatch();
  let nav = useNavigate();

  let fd = useFd();
  const back = () => {
    nav(-1);
  };
  //出发地 目的地 的选择切换
  const saveCity = (name, city) => {
    dis(setCity({ name, city }));
    nav(-1);
  };

  let [list, setList] = useState([]);
  //城市搜索
  const change = fd(async (kw) => {
    let { data: res } = await searchCity(kw);
    console.log(res);
    setList(res);
  });
  const search = (kw) => {
    if (kw.length !== 0) {
      change(kw);
    } else {
      setList([]);
    }
  };
  return (
    <div className={styles.box}>
      <NavBar onBack={back} className={styles.navbox}>
        <SearchBar onChange={search} placeholder="请输入内容" />
      </NavBar>
      {list.length !== 0 ? (
        <div>
          <CitySearch saveCity={saveCity} list={list} />
          <SearchHistory saveCity={saveCity}></SearchHistory>
        </div>
      ) : (
        <div>
          <CityTop saveCity={saveCity} />
          <Citylist saveCity={saveCity} />
        </div>
      )}
    </div>
  );
}

export default Index;
export const loader = async () => {
  let { data: res } = await getCityLocation();
  let { data: ress } = await getCity();
  return { location: res.city, hot: ress.hotCities, list: ress.cityList };
};
